function writemidi(nmat, ofname, tpq, tempo, tsig1, tsig2, inst_num)
% function writemidi(nmat, ofname, tpq, tempo, tsig1, tsig2, inst_num)
%
% Creates a MIDI file from an nmat using various optional parameters
%
% Input: 
%   nmat     [mat] - The notematrix
%   ofnam    [str] - Output filename (*.mid)
%  (Optional)
%   tpq      [num] - Ticks per quarter note (default 120)
%   tempo    [num] - Desired tempo in beats per minute (default 100)
%   tsig1    [num] - Time-signature numerator, e.g. 6/8 -> tsig1 = 6 (default 4)
%   tsig2    [num] - Time-signature denominator, e.g. 6/8 -> tsig2 = 8 (default 4)
%   inst_num [vec] - Program number to use for this track, [] means none 
%
% Output: (writes a MIDI file)
%
% Remarks: TEXT2MIDI converter needs to be handled differently in PC and Mac.
%
% Example: writemidi(a,'demo.mid'); creates a file name DEMO.MID from notematrix A with
% default settings. 
%

% Author		Date
% T. Eerola	1.2.2003
% Part of the MIDI Toolbox, Copyright 2004, University of Jyvaskyla, Finland
% See License.txt
%
% Modified on 02/17/2009 by Graham Grindlay (grindlay@ee.columbia.edu) to
% add support for different instruments per channel via program change
% messages.
% Modified on 08/16/2010 by Graham Grindlay (grindlay@ee.columbia.edu) to
% fix the way the temporary file is created so that files with paths are
% supported.
%

% Copyright (C) 2010-2030 Graham Grindlay (grindlay@ee.columbia.edu)
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

if isempty(nmat), return; end
if nargin <2, ofname = 'temp.mid'; end
if nargin <3, tpq=120; end
if nargin <4, tempo=100; end
if nargin <5, tsig1=4; end
if nargin <6, tsig2=4; disp('Default parameters used'); end
if nargin <7, inst_num = []; end

% Create a temporary text filename
%[ofname0 = strrep(ofname, 'mid', 'txt');

[pstr,name] = fileparts(ofname);
ofname0 = [pstr '/' name '.txt'];

% Convert to text file
nmat2mft(nmat, ofname0, tpq, tempo, tsig1, tsig2, inst_num);

% Convert to MIDI file
mft2mf(ofname0,ofname)

% Delete text file
delete(ofname0)
